import 'package:flutter/material.dart';
import '../models/folder_model.dart';
import '../theme/app_theme.dart';
import 'folder_tree_view.dart';

/// 现代化侧边栏组件
/// 包含用户头像、搜索框、笔记分类和文件夹管理
class ModernSidebar extends StatefulWidget {
  final VoidCallback? onNewNote;
  final VoidCallback? onSettings;
  final Function(String)? onCategorySelected;
  final Function(String)? onFolderSelected;

  const ModernSidebar({
    super.key,
    this.onNewNote,
    this.onSettings,
    this.onCategorySelected,
    this.onFolderSelected,
  });

  @override
  State<ModernSidebar> createState() => _ModernSidebarState();
}

class _ModernSidebarState extends State<ModernSidebar> {
  final TextEditingController _searchController = TextEditingController();
  String _selectedCategory = '全部笔记';
  String _selectedFolder = '';
  
  // 文件夹数据
  List<FolderModel> _folders = [
    FolderModel(
      id: '1',
      name: '工作笔记',
      createdAt: DateTime.now(),
      updatedAt: DateTime.now(),
      icon: Icons.work,
      color: Colors.blue,
      childrenIds: ['2', '3'],
      isExpanded: true,
    ),
    FolderModel(
      id: '2',
      name: '项目文档',
      parentId: '1',
      createdAt: DateTime.now(),
      updatedAt: DateTime.now(),
      icon: Icons.description,
      childrenIds: [],
    ),
    FolderModel(
      id: '3',
      name: '会议记录',
      parentId: '1',
      createdAt: DateTime.now(),
      updatedAt: DateTime.now(),
      icon: Icons.meeting_room,
      childrenIds: [],
    ),
    FolderModel(
      id: '4',
      name: '个人笔记',
      createdAt: DateTime.now(),
      updatedAt: DateTime.now(),
      icon: Icons.person,
      color: Colors.green,
      childrenIds: ['5'],
      isExpanded: false,
    ),
    FolderModel(
      id: '5',
      name: '学习笔记',
      parentId: '4',
      createdAt: DateTime.now(),
      updatedAt: DateTime.now(),
      icon: Icons.school,
      childrenIds: [],
    ),
  ];

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  /// 构建用户头像区域
  Widget _buildUserSection() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Row(
        children: [
          // 用户头像
          Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              color: AppTheme.primaryColor,
              borderRadius: BorderRadius.circular(16),
            ),
            child: const Center(
              child: Text(
                'U',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ),
          const SizedBox(width: 12),
          // 用户名
          const Expanded(
            child: Text(
              '未登录',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: AppTheme.textPrimary,
              ),
            ),
          ),
          // 设置按钮
          IconButton(
            onPressed: widget.onSettings,
            icon: const Icon(Icons.settings_outlined),
            iconSize: 20,
            color: AppTheme.textSecondary,
            padding: EdgeInsets.zero,
            constraints: const BoxConstraints(
              minWidth: 24,
              minHeight: 24,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建搜索框
  Widget _buildSearchBox() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      child: TextField(
        controller: _searchController,
        decoration: InputDecoration(
          hintText: '搜索笔记',
          prefixIcon: const Icon(
            Icons.search,
            size: 20,
            color: AppTheme.textTertiary,
          ),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8),
            borderSide: const BorderSide(color: AppTheme.borderColor, width: 1),
          ),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8),
            borderSide: const BorderSide(color: AppTheme.borderColor, width: 1),
          ),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8),
            borderSide: const BorderSide(color: AppTheme.primaryColor, width: 1),
          ),
          filled: true,
          fillColor: AppTheme.surfaceLight,
          contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          hintStyle: const TextStyle(
            color: AppTheme.textTertiary,
            fontSize: 14,
          ),
        ),
        style: const TextStyle(
          fontSize: 14,
          color: AppTheme.textPrimary,
        ),
      ),
    );
  }

  /// 构建新建笔记按钮
  Widget _buildNewNoteButton() {
    return Container(
      margin: const EdgeInsets.all(16),
      child: SizedBox(
        width: double.infinity,
        child: ElevatedButton.icon(
          onPressed: widget.onNewNote,
          icon: const Icon(Icons.add, size: 18),
          label: const Text('新笔记'),
          style: ElevatedButton.styleFrom(
            backgroundColor: AppTheme.primaryColor,
            foregroundColor: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
            padding: const EdgeInsets.symmetric(vertical: 12),
            elevation: 0,
          ),
        ),
      ),
    );
  }

  /// 构建分类项
  Widget _buildCategoryItem(String title, IconData icon, int count) {
    final isSelected = _selectedCategory == title;
    
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
      child: ListTile(
        leading: Icon(
          icon,
          size: 20,
          color: isSelected ? AppTheme.primaryColor : AppTheme.textSecondary,
        ),
        title: Text(
          title,
          style: TextStyle(
            fontSize: 14,
            fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
            color: isSelected ? AppTheme.primaryColor : AppTheme.textPrimary,
          ),
        ),
        trailing: Text(
          count.toString(),
          style: TextStyle(
            fontSize: 12,
            color: isSelected ? AppTheme.primaryColor : AppTheme.textSecondary,
          ),
        ),
        selected: isSelected,
        selectedTileColor: AppTheme.sidebarSelected,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
        contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
        onTap: () {
          setState(() {
            _selectedCategory = title;
          });
          widget.onCategorySelected?.call(title);
        },
      ),
    );
  }

  /// 构建文件夹列表
  Widget _buildFoldersList() {
    return FolderTreeView(
      folders: _folders,
      selectedFolderId: _selectedFolder,
      onFolderSelected: _onFolderTap,
      onFolderMoved: _onFolderDrop,
      onFolderExpansionChanged: _onFolderExpansionChanged,
      onFolderEdit: _showEditFolderDialog,
      onFolderDelete: _showDeleteFolderDialog,
      onAddFolder: _showAddFolderDialog,
    );
  }

  /// 处理文件夹点击
  void _onFolderTap(FolderModel folder) {
    setState(() {
      _selectedFolder = folder.id;
    });
    widget.onFolderSelected?.call(folder.id);
  }

  /// 处理文件夹拖拽
  void _onFolderDrop(FolderModel draggedFolder, FolderModel targetFolder) {
    setState(() {
      // 从原父文件夹中移除
      if (draggedFolder.parentId != null) {
        final oldParent = _folders.firstWhere((f) => f.id == draggedFolder.parentId);
        final updatedOldParent = oldParent.copyWith(
          childrenIds: oldParent.childrenIds.where((id) => id != draggedFolder.id).toList(),
        );
        _updateFolder(updatedOldParent);
      }
      
      // 添加到新父文件夹
      final updatedTargetFolder = targetFolder.copyWith(
        childrenIds: [...targetFolder.childrenIds, draggedFolder.id],
        isExpanded: true, // 自动展开目标文件夹
      );
      _updateFolder(updatedTargetFolder);
      
      // 更新被拖拽文件夹的父ID
      final updatedDraggedFolder = draggedFolder.copyWith(
        parentId: targetFolder.id,
      );
      _updateFolder(updatedDraggedFolder);
    });
  }

  /// 处理文件夹展开/收起
  void _onFolderExpansionChanged(FolderModel folder) {
    _updateFolder(folder);
  }

  /// 更新文件夹
  void _updateFolder(FolderModel updatedFolder) {
    setState(() {
      final index = _folders.indexWhere((f) => f.id == updatedFolder.id);
      if (index != -1) {
        _folders[index] = updatedFolder;
      }
    });
  }

  /// 显示编辑文件夹对话框
  void _showEditFolderDialog(FolderModel folder) {
    // TODO: 实现编辑文件夹功能
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('编辑文件夹: ${folder.name}')),
    );
  }

  /// 显示删除文件夹对话框
  void _showDeleteFolderDialog(FolderModel folder) {
    // TODO: 实现删除文件夹功能
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('删除文件夹: ${folder.name}')),
    );
  }

  /// 显示添加文件夹对话框
  void _showAddFolderDialog() {
    // TODO: 实现添加文件夹功能
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('添加新文件夹')),
    );
  }

  /// 构建分割线
  Widget _buildDivider() {
    return const Padding(
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Divider(
        height: 1,
        color: AppTheme.borderColor,
      ),
    );
  }

  /// 构建分组标题
  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(24, 16, 16, 8),
      child: Text(
        title,
        style: const TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.w600,
          color: AppTheme.textSecondary,
          letterSpacing: 0.5,
        ),
      ),
    );
  }

  /**
   * 构建用户头部区域
   */
  Widget _buildUserHeader() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: const BoxDecoration(
        color: AppTheme.backgroundPrimary,
        border: Border(
          bottom: BorderSide(color: AppTheme.borderLight, width: 1),
        ),
      ),
      child: Row(
        children: [
          Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              color: AppTheme.primaryColor,
              borderRadius: BorderRadius.circular(20),
            ),
            child: const Icon(
              Icons.person,
              color: Colors.white,
              size: 20,
            ),
          ),
          const SizedBox(width: 12),
          const Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '未登录',
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color: AppTheme.textPrimary,
                  ),
                ),
                Text(
                  '点击登录',
                  style: TextStyle(
                    fontSize: 12,
                    color: AppTheme.textSecondary,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /**
   * 构建笔记分类区域
   */
  Widget _buildNotesCategories() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionTitle('默认笔记'),
        _buildCategoryItem('全部笔记', Icons.note_outlined, 2),
        _buildCategoryItem('未分类笔记', Icons.description_outlined, 1),
      ],
    );
  }

  /**
   * 构建共享文件夹区域
   */
  Widget _buildSharedFolders() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionTitle('共享文件夹'),
        Container(
          padding: const EdgeInsets.all(24),
          child: const Center(
            child: Text(
              '暂无共享文件夹',
              style: TextStyle(
                fontSize: 12,
                color: AppTheme.textTertiary,
              ),
            ),
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 280,
      decoration: const BoxDecoration(
        color: AppTheme.sidebarBackground,
        border: Border(
          right: BorderSide(color: AppTheme.sidebarBorder, width: 1),
        ),
      ),
      child: Column(
        children: [
          _buildUserHeader(),
          _buildSearchBox(),
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                children: [
                  _buildNotesCategories(),
                  _buildFoldersList(),
                  _buildSharedFolders(),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}